package com.gshrms.web.controller.system;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import com.gshrms.common.core.controller.BaseController;
import com.gshrms.common.core.domain.AjaxResult2;
import com.gshrms.common.exception.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.google.code.kaptcha.Producer;
import com.gshrms.common.config.RuoYiConfig;
import com.gshrms.common.constant.CacheConstants;
import com.gshrms.common.constant.Constants;
import com.gshrms.common.core.domain.AjaxResult;
import com.gshrms.common.core.redis.RedisCache;
import com.gshrms.common.utils.sign.Base64;
import com.gshrms.common.utils.uuid.IdUtils;
import com.gshrms.system.service.ISysConfigService;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@RestController
@Api(value = "获取验证码", tags = "获取验证码")
public class CaptchaController extends BaseController {
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private ISysConfigService configService;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    @ApiOperation("获取图片验证码")
    public AjaxResult2 getCode(HttpServletResponse response) throws IOException {
        AjaxResult2 ajax = AjaxResult2.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = RuoYiConfig.getCaptchaType();
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult2.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }


    /**
     * 生成验证码
     */
    @GetMapping("/captchaSms")
    @ApiOperation("获取短信验证码")
    public AjaxResult captchaSms(String phone) {

        //五分钟之内只能发送一个验证码
        sendCode(phone);

        return success();
    }


    public boolean sendCode(String phone) {
        // 1. 检查24小时内发送次数
        String limitKey = String.format(CacheConstants.SEND_LIMIT_KEY, phone);
        Long sendCount = redisTemplate.opsForValue().increment(limitKey, 1);

        // 首次发送设置24小时过期
        if (sendCount != null && sendCount == 1) {
            redisTemplate.expire(limitKey, 24, TimeUnit.HOURS);
        }

        // 超过限制次数
        if (sendCount != null && sendCount > CacheConstants.MAX_SEND_TIMES) {
            throw new ServiceException("今日短信发送次数已达上限，请24小时后再操作");
        }

        // 2. 生成并存储验证码(自动覆盖旧值)
        String code = generateRandomCode();
        String codeKey = String.format(CacheConstants.CODE_KEY, phone);
        redisTemplate.opsForValue().set(codeKey, code, CacheConstants.CODE_EXPIRE, TimeUnit.SECONDS);

        // 3. 调用短信服务发送验证码
        boolean sendResult = sendSms(phone, code);
        if (!sendResult) {
            throw new ServiceException("发送短信失败");
        }
        return sendResult;
    }

    // 生成6位随机数字
    private String generateRandomCode() {
        return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
    }

    // 模拟短信发送
    private boolean sendSms(String phone, String code) {
        // todo 实际项目替换为真实短信服务调用
        System.out.printf(" 向%s发送验证码：%s%n", phone, code);
        return true;
    }

}
